package cjgl.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cjgl.entity.Student;
import cjgl.entity.Teacher;
import cjgl.service.StudentService;
import cjgl.service.TeacherService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private TeacherService teacherService = new TeacherService(); 
    private StudentService studentService = new StudentService();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("pwd");
		HttpSession session = request.getSession();
		Teacher teacher =teacherService.findByUsernameAndPassword(username,password);
		if(teacher==null) {
			Student student= studentService.findByUsernameAndPassword(username,password);
			if(student==null) {
				response.sendRedirect("login.jsp");
			}else {
				session.setAttribute("user",student);
				request.getRequestDispatcher("jsp/main/stumain2.jsp").forward(request, response);
			}
		}else {
			session.setAttribute("user", teacher);
			request.getRequestDispatcher("jsp/main/main4.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
